package com.shm.leetcode.concurrent;
/**
 * @author: shm
 * @dateTime: 2020/10/18 19:39
 * @description:
 */
class FooBar2 {
    private int n;

    public FooBar2(int n) {
        this.n = n;
    }
    Object object = new Object();
    volatile boolean flag= true;
    public void foo(Runnable printFoo) throws InterruptedException {
        synchronized (object) {
            for (int i = 0; i < n; i++) {
                // printFoo.run() outputs "foo". Do not change or remove this line.
                while (!flag){
                    object.wait();
                }
                    printFoo.run();
                    flag=false;
                    object.notifyAll();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        synchronized (object) {
            for (int i = 0; i < n; i++) {

                // printBar.run() outputs "bar". Do not change or remove this line.
                while (flag){
                    object.wait();
                }
                    printBar.run();
                    flag=true;
                    object.notifyAll();
            }
        }
    }
}